package frame.laxcen.module;

import frame.laxcen.request.Request_0010_11;
import frame.laxcen.response.Response_0010_11;
import tcpclient.v2.RFIDClient;
import frame.util.Ref;

import java.net.InetSocketAddress;

public class RFIDWriter {

    private final RFIDClient client;

    public RFIDWriter(RFIDClient client) {

        this.client = client;
    }

    // 尝试在3秒钟内连接读写器
    // param: address 服务器IP地址及端口号
    // return: 连接成功返回true 连接失败返回false
    public boolean tryConnect(InetSocketAddress address) {

        return client.tryConnect(address);
    }

    // 尝试在若干时间内连接读写器
    // param: address 服务器IP地址及端口号
    // param: millisecond 等待的毫秒数
    // return: 连接成功返回true 连接失败返回false
    public boolean tryConnect(InetSocketAddress address, long millisecond) {

        return client.tryConnect(address, millisecond);
    }

    // 尝试关闭与读写器之间的连接 并正常中断读回调
    // return: 关闭成功返回true 关闭失败返回false
    public boolean tryClose() {

        return client.tryClose();
    }

    // 向读写器发送写指令 并阻塞若干时间 直到反馈信息到达
    // param: request 需要发送的写指令
    // param: millisecond 等待的毫秒数
    // return: 返回写指令的执行结果
    public Ref<Response_0010_11> write(Request_0010_11 request, long millisecond) {

        long begin = System.currentTimeMillis();

        if(!client.trySend(request, millisecond)) return Ref.empty();

        millisecond = millisecond - System.currentTimeMillis() + begin;

        return client.waitForResponse(millisecond, Response_0010_11.class);
    }
}
